package main

import (
	"fmt"

	"github.com/hashicorp/consul/api"
)

var (
	client     *api.Client
	consulConf consConf
)

type consConf struct {
	Datacenter string
	Addr       string
	Prefix     string
	Token      string
}

func initConsul(f string) {
	dc := consConf{}
	err := load(f, &dc)
	if err != nil {
		fmt.Println(err)
		return
	}
	var config = &api.Config{Address: dc.Addr, Token: dc.Token, Datacenter: dc.Datacenter}
	client, err = api.NewClient(config)
	if err != nil {
		fmt.Println(err)
		return
	}
	consulConf = dc
	fmt.Printf("import to consul: %+v\n", consulConf)
}

func importToPath(n node) error {
	if n.Addr == "" {
		return nil
	}
	pair := &api.KVPair{Key: fmt.Sprintf("%s%s/nodes/%s", consulConf.Prefix, n.Role, n.Name()), Value: []byte(n.Value)}
	if _, err := client.KV().Put(pair, nil); err != nil {
		return err
	}
	return nil
}
